package com.sse.redis.listener;

import com.sse.context.SseSessionHolder;
import com.sse.form.SseMessageForm;
import com.sse.service.SseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @title: SseMessagePushListener
 * @Author xu-xiang
 * @Date: 2024/1/27 14:06
 * @description:
 */
@Component
@ConditionalOnBean(SseService.class)
public class SseMessagePushListener implements MessageListener {

    private static final Logger logger = LoggerFactory.getLogger(SseMessagePushListener.class);

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer<?> keySerializer = redisTemplate.getKeySerializer();
        RedisSerializer<?> valueSerializer = redisTemplate.getValueSerializer();

        Object channel = keySerializer.deserialize(message.getChannel());
        Object body = valueSerializer.deserialize(message.getBody());

        logger.info("消息频道: " + channel);
        logger.info("消息内容: " + body);
        this.sendMsg((SseMessageForm) body);
    }

    private void sendMsg(SseMessageForm sseMessageForm) {
        logger.info("用户:{}向用户:{}发送了一条消息:{}", sseMessageForm.getUserId(), sseMessageForm.getTargetId(), sseMessageForm.getMsg());
        SseSessionHolder.send(sseMessageForm.getTargetId(), sseMessageForm.getMsg());
    }
}
